<template>
  <MainLayout title="任务列表">
    <view class="p-12">
      <!-- 顶部切换 -->
      <view class="seg">
        <button :class="{act: tab==='todo'}" @click="switchTab('todo')">待办</button>
        <button :class="{act: tab==='done'}" @click="switchTab('done')">已办</button>
      </view>

      <!-- 搜索 -->
      <view class="filters">
        <input class="ipt" type="text" v-model="keyword" placeholder="搜索项目/部位/任务名" @confirm="reload" />
        <button class="search" @click="reload">查询</button>
      </view>

      <!-- 列表 -->
      <view v-if="items.length">
        <view
            v-for="it in items"
            :key="it.id"
            class="item"
        >
          <!-- CHANGED: 左侧展示区域；整行点击的“默认行为”见 @click（待办→手动填报；已办→查看） -->
          <view class="left" @click="isTodo ? goFillManual(it) : goView(it)">
            <view class="name">{{ it.name }}</view>
            <view class="meta">
              <text>{{ it.projectName }}</text>
              <text>·</text>
              <text>{{ it.deadlineStr }}</text>
            </view>
          </view>

          <!-- NEW: 右侧操作区（根据 tab 显示不同按钮） -->
          <view class="actions" v-if="isTodo">
            <button class="action danger" @click.stop="goFillManual(it)">填报</button>
          </view>
          <view class="actions" v-else>
            <button class="action link" @click.stop="goView(it)">查看</button>
          </view>
        </view>

        <!-- 分页 -->
        <view class="pager" v-if="total > size">
          <button :disabled="page<=1" @click="prev">上一页</button>
          <text class="pg">{{ page }} / {{ totalPages }}</text>
          <button :disabled="page>=totalPages" @click="next">下一页</button>
        </view>
      </view>

      <view v-else class="empty">暂无数据</view>
    </view>
  </MainLayout>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { api } from '@/services/api' // 你的 API 封装
import MainLayout from '@/layouts/MainLayout.vue'

// NEW: 中文标题兜底映射（后端已返回 taskName 时不会用到，防止显示英文类型）
const TITLE_MAP: Record<string, string> = {
  rebar_material: '钢筋原材料检验批',
  rebar_process: '钢筋加工检验批',
  rebar_installation: '钢筋安装检验批',
  formwork_installation: '模板安装检验批',
  concrete_mix: '混凝土拌合物检验批',
  concrete_construction: '混凝土施工记录',
  cast_in_situ_structure: '现浇结构实体检验记录',
}

type ApiItem = {
  taskId: number
  projectId: number
  projectName: string
  taskType: string
  taskLocation: string
  taskName?: string
  taskState: '0' | '1'
  taskStateCn: string
  taskStarttime: string
  taskDeadline: string
}

type UiItem = {
  id: number
  name: string
  projectName: string
  deadlineStr: string
  raw: ApiItem
}

const tab = ref<'todo'|'done'>('todo')
const isTodo = computed(()=> tab.value === 'todo') // NEW: 便于模板里判断
const keyword = ref('')
const page = ref(1)
const size = ref(10)
const total = ref(0)
const items = ref<UiItem[]>([])

const totalPages = computed(()=> Math.max(1, Math.ceil(total.value / size.value)))

// 工具：时间格式化
function fmtDateTime(s?: string) {
  if (!s) return ''
  try {
    const d = s.includes('T') ? new Date(s) : new Date(s.replace(/-/g,'/'))
    const pad = (n:number)=> (n<10?'0':'') + n
    return `${d.getFullYear()}-${pad(d.getMonth()+1)}-${pad(d.getDate())} ${pad(d.getHours())}:${pad(d.getMinutes())}`
  } catch { return s || '' }
}

// CHANGED: 任务名优先用后端的 taskName；如果没有则用中文映射兜底
function toUi(row: ApiItem): UiItem {
  const title = row.taskName || (row.taskLocation ? `${row.taskLocation}-${TITLE_MAP[row.taskType] || row.taskType}` : (TITLE_MAP[row.taskType] || row.taskType))
  return {
    id: row.taskId,
    name: title,
    projectName: row.projectName || '',
    deadlineStr: fmtDateTime(row.taskDeadline),
    raw: row,
  }
}

// 数据加载：带上 state=todo|done，让后端按状态过滤（修复“两个按钮都显示全部”的问题）
async function load() {
  const data = await api.fetchTasks({
    state: tab.value,                  // CHANGED: 关键参数
    page: page.value,
    size: size.value,
    keyword: keyword.value.trim() || undefined,
  })
  total.value = Number(data.total || 0)
  items.value = Array.isArray(data.items) ? data.items.map(toUi) : []
}

// tab & 分页
function switchTab(next: 'todo'|'done'){ if (tab.value!==next){ tab.value=next; page.value=1; load() } }
function reload(){ page.value=1; load() }
function prev(){ if (page.value>1){ page.value--; load() } }
function next(){ if (page.value<totalPages.value){ page.value++; load() } }

// NEW: 跳转动作（按钮/整行点击会用到）
function goFillManual(row: UiItem){
  // 传参：id + type（后端用来选择对应的填报表单）
  uni.navigateTo({ url: `/pages/tasks/fill_manual?id=${row.id}&type=${row.raw.taskType}` })
}
function goFillDevice(row: UiItem){
  uni.navigateTo({ url: `/pages/tasks/fill_device?id=${row.id}&type=${row.raw.taskType}` })
}
function goView(row: UiItem){
  uni.navigateTo({ url: `/pages/tasks/detail?id=${row.id}&type=${row.raw.taskType}` })
}

// 兼容你原有事件
function setTabByEvent(v:'todo'|'done'){ switchTab(v) }
onMounted(()=>{ uni.$on('tasks:setTab', setTabByEvent); uni.$on('tasks:filterAbnormal', ()=>{ tab.value='todo'; reload() }); load() })
onUnmounted(()=>{ uni.$off('tasks:setTab', setTabByEvent); uni.$off('tasks:filterAbnormal') })
</script>

<style scoped>
.p-12{padding:12px}
.seg{display:flex; gap:8px; margin-bottom:12px}
.seg button{flex:1; padding:10px 12px; border-radius:8px; background:#f2f3f5; border:0}
.seg .act{background:#007aff; color:#fff}
.filters{display:flex; gap:8px; margin-bottom:12px}
.ipt{flex:1; padding:8px 10px; border:1px solid #eee; border-radius:8px; background:#fff}
.search{padding:8px 12px; border:0; border-radius:8px; background:#007aff; color:#fff}

/* CHANGED: 列表每行改为左右布局，右侧放操作按钮 */
.item{
  background:#fff; border-radius:12px; padding:12px; margin-bottom:10px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.04);
  display:flex; align-items:center; justify-content:space-between; gap:12px;
}
.left{flex:1; min-width:0;}
.name{font-weight:600; font-size:15px; color:#111}
.meta{color:#8a8a8a; margin-top:6px; font-size:12px; display:flex; gap:6px}

/* NEW: 操作按钮样式 */
.actions{display:flex; gap:8px}
.action{
  padding:6px 10px; border-radius:8px; background:#fff; border:1px solid #eaeaea; font-size:12px;
}
.action.danger{color:#007aff; border-color:#007aff;}
.action.link{color:#007aff; border-color:#007aff;} /* 已办“查看”风格一致 */

.pager{display:flex; align-items:center; justify-content:center; gap:12px; margin-top:12px}
.pg{color:#666}
.empty{color:#999; text-align:center; padding:40px 0}
</style>
